import json
import os

def clean_gs_prefix(gs):
    """移除gs字符串开头的y相关前缀"""
    prefixes = ['y\'', 'y', 'y2\'', 'y2']
    for prefix in prefixes:
        if gs.startswith(prefix):
            # 移除前缀，注意可能需要处理前缀后的空格
            remaining = gs[len(prefix):]
            # 如果前缀后有空格，也移除
            if remaining.startswith(' '):
                return remaining[1:]
            return remaining
    return gs

# 读取detail.json文件
file_path = 'd:/workspace/cfop-random/detail.json'
with open(file_path, 'r', encoding='utf-8') as f:
    data = json.load(f)

# 确保oll和oll_dys字段存在
if 'oll' not in data or 'oll_dys' not in data:
    print('Error: Missing required fields in detail.json')
    exit(1)

# 创建oll分组的gs到name的映射（忽略<br/>和前缀）
oll_gs_map = {}
for item in data['oll']:
    gs_clean = item['gs'].replace('<br/>', '')
    gs_clean = clean_gs_prefix(gs_clean)
    oll_gs_map[gs_clean] = item['name']

# 创建oll_dys分组的gs到name的映射（忽略<br/>和前缀）
oll_dys_gs_map = {}
for item in data['oll_dys']:
    gs_clean = item['gs'].replace('<br/>', '')
    gs_clean = clean_gs_prefix(gs_clean)
    oll_dys_gs_map[gs_clean] = item['name']

# 遍历oll_dys分组，查找匹配的gs并添加ref字段
updated_count_oll_dys = 0
for item in data['oll_dys']:
    gs_clean = item['gs'].replace('<br/>', '')
    gs_clean = clean_gs_prefix(gs_clean)
    if gs_clean in oll_gs_map:
        item['ref'] = oll_gs_map[gs_clean]
        updated_count_oll_dys += 1
    else:
        # 如果之前有ref字段但现在不匹配，移除它
        if 'ref' in item:
            del item['ref']

# 遍历oll分组，查找匹配的gs并添加ref字段
updated_count_oll = 0
for item in data['oll']:
    gs_clean = item['gs'].replace('<br/>', '')
    gs_clean = clean_gs_prefix(gs_clean)
    if gs_clean in oll_dys_gs_map:
        item['ref'] = oll_dys_gs_map[gs_clean]
        updated_count_oll += 1
    else:
        # 如果之前有ref字段但现在不匹配，移除它
        if 'ref' in item:
            del item['ref']

# 保存修改后的文件
output_path = 'd:/workspace/cfop-random/detail_updated.json'
with open(output_path, 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

print(f'比较完成。oll_dys中有{updated_count_oll_dys}个条目已更新ref字段，oll中有{updated_count_oll}个条目已更新ref字段。')

print(f'更新后的文件已保存到: {output_path}')